package com.cndw.kungfu.model;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

import com.cndw.kungfu.core.CacheDataBase;
import com.cndw.kungfu.core.CacheDataKey;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.model.pvp.war.WarCrossData;

public class WarCrossAreaSerialize extends CacheDataBase implements Serializable {
	private static final long serialVersionUID = 1L;

	private WarCrossData warCrossData;

	private int area;

	private String areaKey;

	private static ConcurrentHashMap<Integer, WarCrossAreaSerialize> instanceMap = new ConcurrentHashMap<Integer, WarCrossAreaSerialize>();

	@Override
	public String getKey() {
		return areaKey;
	}

	private WarCrossAreaSerialize() {

	}

	private WarCrossAreaSerialize(int area, WarCrossData warCrossData) {
		this.area = area;
		this.warCrossData = warCrossData;
		areaKey = getKeyInit(area);
	}

	public static String getKeyInit(int area) {
		return CacheDataKey.keyWarCrossAreaSerialize + "_" + area;
	}

	public static WarCrossAreaSerialize getInstance(int area) {
		if (!instanceMap.containsKey(area)) {
			synchronized (WarCrossAreaSerialize.class) {
				if (!instanceMap.containsKey(area)) {
					if (!instanceMap.containsKey(area)) {
						CacheDataBase cacheData = Context.getSysServer().initCacheData(getKeyInit(area));
						WarCrossAreaSerialize instance = null;
						if (cacheData != null && cacheData instanceof WarCrossAreaSerialize) {
							instance = (WarCrossAreaSerialize) cacheData;
						}
						if (instance == null) {
							instance = new WarCrossAreaSerialize(area, new WarCrossData(area));
							LogUtil.getMain().info("warcross data init by new ..." + area);
						}

						if (instance.getSyncDBTime() == 0) {
							instance.commitSync();
						}
						instanceMap.putIfAbsent(area, instance);
					}
				}
			}
		}
		return instanceMap.get(area);
	}

	public WarCrossData getWarCrossData() {
		return warCrossData;
	}

	public int getArea() {
		return area;
	}

	public static void clearCross() {// 只清理一大区
		getInstance(1);
		instanceMap.put(1, new WarCrossAreaSerialize(1, new WarCrossData(1)));
		instanceMap.get(1).commitSync();
	}
	
	public static void allSync(){
		for (WarCrossAreaSerialize e : instanceMap.values()) {
			e.commitSync();
		}
	}

}
